package com.qf.crud.controller;

import com.qf.crud.common.R;
import com.qf.crud.entity.Student;
import com.qf.crud.entity.vo.StudentVO;
import com.qf.crud.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("stu")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("findById")
    public R findById(Integer id){
        Student student = studentService.findById(id);
        return R.ok(student);
    }

    @GetMapping("list")
    public R findAll(){
        List<Student> list = studentService.findAll( );
        return R.ok(list);
    }

    // 模糊查询
    @GetMapping("/search")
    public R findAll(@RequestParam HashMap<String,Object> map){
        List<Student> list = studentService.findByKeyword(map);
        return R.ok(list);
    }

    // 添加数据
    @PostMapping("/add")
    public R add(Student student){
        studentService.add(student);
        return R.ok();
    }

    // 更新数据(全表更新)
    @PostMapping("/edit")
    public R edit(Student student){
        studentService.edit(student);
        return R.ok();
    }

    // 删除数据
    @GetMapping("/del")
    public R del(int id){
        studentService.deleteById(id);
        return R.ok();
    }

    // 批量删除
    @GetMapping("/del/batch")
    public R batchDelete(@RequestParam List<Integer> ids){
        if (ids == null || ids.size() == 0){
            return R.error("没选择用户id");
        }
        int count = studentService.batchDelete(ids);
        if (count == 0){
            return R.error("删除失败");
        }
        return R.ok(count);
    }

    // 查询所有学生信息以及关联的班级信息(一对一)
    @GetMapping("/class")
    public R findAllStudentAndClassroom(){
        List<StudentVO> list = studentService.findAllStudentAndClassroom( );
        return R.ok(list);
    }

    // 查询一个学生信息以及关联的所有学科信息(一对多)
    @GetMapping("/subjects")
    public R findStudentAndAllSubjectByStuid(int sid){
        StudentVO studentVO = studentService.findStudentAndAllSubjectByStuid(sid);
        return R.ok(studentVO);
    }
}